# -*- coding:utf-8 -*-
#-------------------------------
# 解压zip文件
# 张力2009年11月20日 09:31:50
# 注意應該多運行幾次此腳本,因為可能解壓縮的文件夾中仍然包含壓縮文件
#-------------------------------
import sys, os, zipfile

def DirCreate(dir):
  if not os.path.exists(dir):
    os.mkdir(dir)
def decompression(targetfilepath,tofolder):
    z = zipfile.ZipFile(targetfilepath, 'r')
    DirCreate(tofolder)
    for f in z.namelist():
        path = os.path.join(tofolder, f)
        if path.endswith("/"):
            DirCreate(path)
        else:
            file(path, 'wb').write(z.read(f))
#-----------------------------------
# 使用7z解压
# 兩個參數都是全路徑
#-----------------------------------
def decompressionuse7z(targetfilepath,tofolder):
    os.system(('7Z x -o\"'+tofolder+'\" \"'+targetfilepath+'\"'))

def decompressionuserar(targetfilepath,tofolder):
    print(('unrar x -r\"'+targetfilepath+'\" \"'+tofolder+'\"'))
    os.system(('unrar x -r \"'+targetfilepath+'\" \"'+tofolder+'\"'))
    
basepath = 'C:\\Users\\tingwei\\Desktop\\mm'
#--------------------------------
# 遍历目录把路径保存在 filelist中
#--------------------------------
filelist = []
for root, dirs, files in os.walk(basepath):
    for name in files:
        #global filelist
        if name != 'recovery.py':
            filelist.append(os.path.join(root,name))

#---------------------------------
# 篩選 要處理的文件
#---------------------------------
for i in filelist:
    filetype = i.rsplit('.',1)[-1].lower()
    if filetype == 'rar':
        decompressionuserar(i,i+'_decompress\\')
        #os.remove(i)
    elif filetype == 'zip':
        decompression(i,i+'_decompress')
    elif filetype == '7z':
        decompressionuse7z(i,i+'_decompress')
    print('\ndone')

